<template>
  <main
    class="login-main"
    v-loading="loading"
    element-loading-text="拼命加载中"
  >
    <div class="login-window">
      <el-form
        :rules="rules"
        label-position="left"
        label-width="80px"
        :model="loginForm"
      >
        <el-form-item label="用户名" prop="UserName">
          <el-input
            placeholder="请输入用户名"
            v-model="loginForm.UserName"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="Password">
          <el-input
            placeholder="请输入密码"
            show-password
            v-model="loginForm.Password"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        @click="login"
        :disabled="!loginEnable"
        type="primary"
        class="login-button"
        >登陆</el-button
      >
      <el-button
        @click="gotoCASLogin"
        type="plain"
        class="login-button"
      >
        单点登陆
      </el-button>
    </div>
  </main>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        UserName: '',
        Password: '',
        Platform: 'w'
      },
      rules: {
        UserName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        Password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      },
      loading: false
    }
  },
  computed: {
    loginEnable () {
      return (
        this.loginForm.UserName.length > 0 && this.loginForm.Password.length > 0
      )
    }
  },
  mounted () {
    const ticket = this.$route.query.ticket
    console.log(ticket)
    if (ticket) {
      this.loginCAS(ticket)
    }
  },
  methods: {
    async login () {
      try {
        this.loading = true
        const result = await this.$net.post('/login', this.loginForm)
        await this.$store.dispatch('didLogin', result.data.Token)
        this.$router.push('/my_apps')
      } finally {
        this.loading = false
      }
    },
    gotoCASLogin () {
      window.location.href = process.env.VUE_APP_CAS_HOST + '/login?service=' + this.loginService()
    },
    async loginCAS (ticket) {
      try {
        this.loading = true
        const result = await this.$net.post('/login/cas', {
          Ticket: ticket,
          Service: this.loginService(),
          Platform: 'w'
        })
        await this.$store.dispatch('didLogin', result.data.Token)
        this.$router.push('/my_apps')
      } finally {
        this.loading = false
      }
    },
    loginService () {
      return window.location.origin + '/login'
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
}
.login-window {
  padding: 50px;
  max-width: 350px;
  height: 200px;
  margin: 100px auto 0 auto;
  display: flex;
  gap:20px;
  flex-direction: column;
}
.login-button {
  width: 100%;
  margin: 0 auto;
}
</style>
